package app

import (
	"aglaia/global"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	AuthId uint   `json:"auth_id"`
	AppKey string `json:"app_key"`
	//AppSecret string `json:"app_secret"`
	jwt.StandardClaims
}

func GetJWTSecret() []byte {
	return []byte(global.JWTSetting.Secret)
}

func GenerateToken(authId uint, appKey, appSecret string) (token string, err error) {
	now := time.Now()
	expireTime := now.Add(global.JWTSetting.Expire)
	claims := Claims{
		AuthId: authId,
		AppKey: appKey,
		//AppSecret: util.Encrypt(appSecret, md5.New()),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    global.JWTSetting.Issuer,
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return tokenClaims.SignedString(GetJWTSecret())
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return GetJWTSecret(), nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
